﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace SvnMonitor
{
    static class TortoiseSVN
    {
        public static void UpdateWorkingCopy(IRepositoryMonitor repositoryMonitor)
        {
            var section = ConfigurationManager.GetSection("TortoiseSVN") as TortoiseSVNConfigSection;
            if (section == null)
            {
                // create section with default values
                Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
                config.Sections.Add("TortoiseSVN", new TortoiseSVNConfigSection
                {
                    TortoiseProc = @"c:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"
                });
                config.Save();

                ViewManager.ShowMessage("There are no TortoiseSVN settings in the application configuration file.\n\rDefault configuration settings has been created.\n\r\n\r" +
                                        "Please specify correct settings for TortoiseSVN in the configuration file and restart application.", "Svn Monitor");
            }
            else
            {
                ProcessStartInfo startInfo = new ProcessStartInfo(section.TortoiseProc, string.Format("/command:update /path:\"{0}\" /closeonend:0", repositoryMonitor.WorkingCopy));
                startInfo.UseShellExecute = true;

                Process process = Process.Start(startInfo);
                process.EnableRaisingEvents = true;
                process.Exited += delegate
                {
                    // force repository check
                    repositoryMonitor.CheckNow();
                };
            }
        }
    }
}
